﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Print_UI
{
    public partial class FrmSubjectSettingIT : CommonForm
    {
        public FrmSubjectSettingIT()
        {
            InitializeComponent();
        }
        #region Private members
        private int _id = -1;
        DataTable table = new DataTable();
        DataTable ew = new DataTable();
        #endregion
        #region Event
        //load form SubjectSeeting
        private void FrmSubjectSettingIT_Load(object sender, EventArgs e)
        {
            table.Columns.Add("SubjectID", typeof(int));
            table.Columns.Add("Code", typeof(string));
            table.Columns.Add("SubjectName", typeof(string));
            table.Columns.Add("Check", typeof(bool));
            table.Columns.Add("TeacherID", typeof(int));
            btnSave.Enabled = false;
            LoadYear();
            LoadTeachcher();
        }
        #region Loaddata
        private void cboClass_EditValueChanged(object sender, EventArgs e)
        {
            checkused();
            LoadTeachcher();
            LoadData();
        }
        private void cboYear_EditValueChanged(object sender, EventArgs e)
        {
            checkused();
            LoadSemester();
            LoadClass();
            LoadData();
        }
        private void cboSemester_EditValueChanged(object sender, EventArgs e)
        {
            dxErrorProvider1.ClearErrors();
            checkused();
            LoadClass();
            LoadData();
        }
        //check year is used
        private void checkused()
        {
            int year = Convert.ToInt32(cboYear.EditValue);
            int semester = Convert.ToInt32(cboSemester.EditValue);
            bool check = Model.PRI_SemesterSetting.Where(c => c.YearID == year && c.SemesterID == semester && c.IsUsed == true).Count() > 0;
            if (check)
            {
                btnSave.Enabled = true;
            }
            else
            {
                btnSave.Enabled = false;
            }
        }
        #endregion
        //button Cancel
        private void btnCancel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (MessageBox.Show("Thoát giao diện này", "Thông báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                this.Close();
        }
        //button save
        private void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //check semester is used
            int iyearID = Convert.ToInt32(cboYear.EditValue);
            int iSemesterID = Convert.ToInt32(cboSemester.EditValue);
            int iClass = Convert.ToInt32(cboClass.EditValue);
            bool check = Model.PRI_SemesterSetting.Where(c => c.YearID == iyearID && c.SemesterID == iSemesterID && c.IsUsed == true).Count() > 0;
           
            if (check)
            {
               
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        int iSubjectID = Convert.ToInt32(table.Rows[i]["SubjectID"]);
                        bool ismain = Convert.ToBoolean(table.Rows[i]["Check"]);
                        int iteacherID = Convert.ToInt32(table.Rows[i]["TeacherID"]);
                        var obj = Model.PRI_SubjectSetting.Where(c => c.SubjectID == iSubjectID && c.ClassID == iClass && c.YearID == iyearID && c.SemesterID == iSemesterID).FirstOrDefault();
                        if (obj != null)
                        {
                            obj.ModifiedDate = DateTime.Now;
                            obj.ModifiedBy = UserName;
                            obj.IsMain = ismain;
                            if (iteacherID != -1)
                            {
                                obj.TeacherID = iteacherID;
                            }
                        }
                    }
                    Model.SaveChanges();
                    //// return TeacherID of datatable
                    //for (int i = 0; i < table.Rows.Count; i++)
                    //{
                    //    int iSubjectID = Convert.ToInt32(table.Rows[i]["SubjectID"]);
                    //    bool ismain = Convert.ToBoolean(table.Rows[i]["Check"]);
                    //    int iteacherID = Convert.ToInt32(table.Rows[i]["TeacherID"]);
                    //    var obj = Model.PRI_SubjectSetting.Where(c => c.SubjectID == iSubjectID && c.ClassID == iClass && c.YearID == iyearID && c.SemesterID == iSemesterID).FirstOrDefault();
                    //    if (obj != null)
                    //    {
                    //        table.Rows[i]["TeacherID"] = obj.TeacherID;
                    //    }
                    //}

                    CommonMessage("Cập nhật thành công");

                    _id = -1;
                    LoadData();
                
                
            }
            else
            {
                dxErrorProvider1.SetError(cboSemester, "Học kì hiện tại của năm học đã bị khóa");

            }
        }
        #endregion
        #region Private members
        //load combobox year
        private void LoadYear()
        {
            var Year = (from p in Model.CAT_Year
                        join k in Model.PRI_SemesterSetting on p.ID equals k.YearID
                        select new { p.ID, p.Name }).Distinct();
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(-1, "---Chọn Năm Học---");
            foreach (var item in Year)
            {
                dic.Add(item.ID, item.Name);
            }

            cboYear.Properties.ValueMember = "Key";
            cboYear.Properties.DisplayMember = "Value";
            cboYear.Properties.DataSource = dic;
            cboYear.EditValue = _id;
        }
        //load combobox semester
        private void LoadSemester()
        {
            int i = Convert.ToInt32(cboYear.EditValue);
            var Semester = (from p in Model.CAT_Semester
                            join k in Model.PRI_SemesterSetting on p.ID equals k.SemesterID
                            where i == k.YearID
                            select new { p.ID, p.SemesterName }).Distinct();
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(-1, "--- Chọn Học Kì ---");
            foreach (var item in Semester)
            {
                dic.Add(item.ID, item.SemesterName);
            }
            cboSemester.Properties.ValueMember = "Key";
            cboSemester.Properties.DisplayMember = "Value";
            cboSemester.Properties.DataSource = dic;
            cboSemester.EditValue = _id;
        }
        //load combobox class
        private void LoadClass()
        {

            try
            {
                int iYear = Convert.ToInt32(cboYear.EditValue);
                int iSemester = Convert.ToInt32(cboSemester.EditValue);
                var GetClass = (from obj in Model.PRI_SubjectSetting.Where(c => c.DepartmentID == DepartmentID && c.YearID == iYear && c.SemesterID == iSemester)
                                select new { obj.CAT_Class.ID, obj.CAT_Class.Name }).Distinct();
                Dictionary<int, string> dic = new Dictionary<int, string>();
                dic.Add(-1, "---Chọn Lớp---");
                foreach (var item in GetClass)
                {
                    dic.Add(item.ID, item.Name);
                }
                cboClass.Properties.ValueMember = "Key";
                cboClass.Properties.DisplayMember = "Value";
                cboClass.Properties.DataSource = dic;
                cboClass.EditValue = -1;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //load data in datagridview
        private void LoadData()
        {
            labelControl2.Visible = false;
            table.Clear();
            int iYear = Convert.ToInt32(cboYear.EditValue);
            int iSemester = Convert.ToInt32(cboSemester.EditValue);
            int iClass = Convert.ToInt32(cboClass.EditValue);
            var query = Model.PRI_SubjectSetting.Where(c => c.DepartmentID == DepartmentID &&
                c.ClassID == iClass && c.YearID == iYear && c.SemesterID == iSemester).Select(c => new
                {
                    c.SubjectID,
                    c.TeacherID,
                    TeacherSuggest = 
                        (c.TeacherID == null &&
                        c.PRI_Subjects.PRI_SubjectSetting.Where(d => d.TeacherID != null && d.DepartmentID == DepartmentID).Count() > 0) ?
                        c.PRI_Subjects.PRI_SubjectSetting.Where(d => d.TeacherID != null && d.DepartmentID == DepartmentID).OrderByDescending(d => d.CreatedDate).Select(d => d.TeacherID).FirstOrDefault() : -1,
                    SubjectsCode = c.PRI_Subjects.Code,
                    c.PRI_Subjects.SubjectName,
                    c.IsMain
                });
            bool isNew = Model.PRI_SubjectSetting.Where(c => c.DepartmentID == DepartmentID &&
                c.ClassID == iClass && c.YearID == iYear && c.SemesterID == iSemester && c.TeacherID != null).Count() == 0;
            int count = 0;
            foreach (var item in query)
            {
                DataRow dr = table.NewRow();
                if (item.TeacherSuggest == -1)
                {
                    count++;
                }
                if (isNew == true)
                {
                    dr["TeacherID"] = item.TeacherSuggest;
                    
                    labelControl2.Visible = true;
                }
                else
                {
                    if (item.TeacherID == null)
                    {
                        dr["TeacherID"] = -1;
                    }
                    else if (item.TeacherID != null)
                    {
                        dr["TeacherID"] = item.TeacherID;
                    }
                    labelControl2.Visible = false;
                }
                dr["SubjectID"] = item.SubjectID;
                dr["Code"] = item.SubjectsCode;
                dr["SubjectName"] = item.SubjectName;
                dr["Check"] = item.IsMain;
                table.Rows.Add(dr);
            }
            if (count == table.Rows.Count)
            {
                labelControl2.Visible = false;
            }
            gvdSubject.DataSource = table;


        }
        //load teacher
        private void LoadTeachcher()
        {
            // load values ID for repositoryItemLookUpEdit1
            try
            {
                var Teacher = Model.PRI_Teacher.Where(c => c.DepartmentID == DepartmentID);
                repositoryItemLookUpEdit1.DataSource = Teacher;
                repositoryItemLookUpEdit1.DisplayMember = "Name";
                repositoryItemLookUpEdit1.ValueMember = "ID";
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }
        #endregion
    }
}


